import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:text_world/api.dart';
import 'sqlite_util.dart';

class MainManager with ChangeNotifier {
  static MainManager instance = MainManager();
  Map hitokoto = {
    'id': '',
    'hitokoto': '',
    'card_type': 'g',
    'from': '',
    'from_who': 'hitokoto'
  };

  Map yiwen = {
    'date': null,
    'author': '',
    'title': '',
    'digest': '',
    'content': '',
    'wc': ''
  };

  List likeList = [];
  final sqliteUtil = SqliteUtil();

  void init() async {
    sqliteUtil.createDb(1);
    // clearDb();
    refreshLikeList();

    getNewHitokoto();
    getNewMeiRiYiWen();
  }

  getNewHitokoto() {
    getHitokoto().then((res) {
      hitokoto = json.decode(res.toString());
      hitokoto['card_type'] = 'hitokoto';
      notifyListeners();
    });
  }

  getNewMeiRiYiWen() {
    getMeiRiYiWen().then((res) {
      yiwen = json.decode(res.toString())['data'];
      yiwen['card_type'] = 'yiwen';
      notifyListeners();
    });
  }

  Future queryAll() async {
    return query("select * from TextWorld");
  }

  void clearDb() {
    sqliteUtil.delete("DELETE FROM TextWorld");
  }

  Future query(sql) async {
    return sqliteUtil.query(sql);
  }

  bool isLike(text) {
    return !likeList.every((item) {
      return (item['id'].toString() != text['id'].toString());
    });
  }

  void like(text) async {
    if (!isLike(text)) {
      likeList.add(text);
    } else {
      likeList.removeWhere((item) {
        return (item['id'].toString() == text['id'].toString()) &&
            (item['card_type'].toString() == text['card_type'].toString());
      });
    }

    update(likeList);
    refreshLikeList();
  }

  void insert(likeList) async {
    await sqliteUtil.insert(
        'INSERT INTO TextWorld(id,likeList) VALUES("1","${json.encode(likeList)}")');
    refreshLikeList();
  }

  void update(likeList) async {
    await sqliteUtil.update('UPDATE TextWorld SET likeList = ? WHERE id = "1"',
        [json.encode(likeList)]);
    refreshLikeList();
  }

  void delete() async {
    await sqliteUtil.delete('DELETE FROM TextWorld WHERE id = "1"');
    refreshLikeList();
  }

  refreshLikeList() {
    queryAll().then((res) {
      if (res.length == 0) {
        insert([]);
        likeList = [];
        notifyListeners();
      } else {
        likeList = json.decode(res[0]['likeList']);
        notifyListeners();
      }
    });
  }
}
